var AV = require('leanengine');
var common = require('../../cloud/common');
let async = require('async')
let rp = require('request-promise');
/**
 * 手动给特定部落添加成员。
 */
AV.Cloud.define("manuallyAddPersonnel", function (request, response) {

    let options = {
        method: 'POST',
        uri: 'http://localhost:3000/getdata/login',
        headers: {
            'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'  // Is set automatically
        },
        form: {username:'18210969169',password:'aaaaaa'}
    }

    rp(options).then(body => {
        console.log(body,'-=--=--=-=-=')

    }).catch(error => {
        console.log(error,'-=-=--=--=')

        // return error
    })



    let userQuery = new AV.Query('_User')
    userQuery.limit(300)
    userQuery.descending('createdAt')
    userQuery.find().then(results => {
        let count = 1;
        async.eachSeries(results, async (item, callback) => {
            let flag = await checkExistInGivenTribe(item.id)
            if (flag) {
                count++
                callback(null)
                return
            }
            console.log(item.id,'item.id')
            var data = {
                userOId: item.id,
                tribeOId: '5ab9b739ee920a0045e3c083',

                userType: '3'
            };


            let options = {
                method: 'POST',
                uri: 'http://localhost:3000/tribeRoute/manuAddTribeMember',
                headers: {
                    'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'  // Is set automatically
                },
                form: data
            }

            rp(options).then(body => {
                console.log(body)
                return callback(null)
            }).catch(error => {
                console.log(error,'-=-=--=--=')
                return callback(null)
                // return error
            })


        },function (end) {
            console.log(count)
        })


    })
})

function checkExistInGivenTribe(userOId, {tribeOId = '5aa869369f54540045665ef5'} = {}) {
    let query = new AV.Query('TribeMember')
    query.equalTo('tribeOId', tribeOId)
    query.equalTo('userOId', userOId)
    return query.first().then(res => {
        if (res) {
            return true
        } else return false
    })

}


